﻿using Inaction.Rule;
using System;
using System.IO;

namespace Inaction.Core
{
    public abstract class BaseSerializer
    {
        public abstract SerializeType SerializeType { get; }

        #region Serializer
        #region abstract
        public abstract string SerializeToString(object obj);
        public abstract byte[] Serialize(object obj);
        public abstract T Deserialize<T>(byte[] data) where T : class;
        public abstract object Deserialize(Type type, byte[] data);

        private object flag = 0;
        #endregion

        public virtual void SerializeToFile(object obj, string fileName)
        {
            lock (flag)
            {
                using (var fs = new FileStream(fileName, FileMode.Create))
                {
                    var content = Serialize(obj);
                    foreach (var b in content)
                    {
                        fs.WriteByte(b);
                    }
                    fs.Flush();
                    fs.Close();
                    fs.Dispose();
                }
            }
        }

        #endregion

        #region Deserialize
        public virtual T DeserializeFormString<T>(string str) where T : class
        {
            return Deserialize<T>(System.Text.Encoding.Unicode.GetBytes(str));
        }
        public virtual T DeserializeFormFile<T>(string fileName) where T : class
        {
            if (!File.Exists(fileName))
            {
                throw new ArgumentNullException();
            }
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                var buf = new byte[fs.Length];
                fs.Read(buf, 0, buf.Length);
                var obj = Deserialize<T>(buf);
                fs.Close();
                fs.Dispose();
                return obj;
            }
        }
        #endregion
    }
}
